package com.qf.admin.shiro;



import com.qf.common.response.ResponseEnum;
import com.qf.entity.dto.Admin;
import com.qf.entity.po.LoginAdmin;
import com.qf.service.AdminService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 自定义Realm
 */
public class LoginRealm extends AuthorizingRealm {

    @Autowired
    private AdminService adminService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return new SimpleAuthorizationInfo();
    }

    /**
     * 登录验证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String username = token.getUsername();
        String password = new String(token.getPassword());
        Admin admin = adminService.getByUserNamePwd(username,password);
        if (admin == null) {
            throw new RuntimeException(ResponseEnum.LOGIN_FAIL.getMessage());
        }
        LoginAdmin loginAdmin = new LoginAdmin();
        loginAdmin.setId(admin.getId());
        loginAdmin.setName(admin.getName());
        loginAdmin.setDescription(admin.getDescription());
        loginAdmin.setRoleId(admin.getRoleId());
        loginAdmin.setCreateTime(admin.getCreateTime());
        return new SimpleAuthenticationInfo(loginAdmin, admin.getPassword(), admin.getUsername());
    }
}
